﻿///////////////////////////////////////////////////////////////////////////////
// File:        Main.cc
// Author:      671643387@qq.com
// Date:        2016年1月18日 上午9:36:42
// Description:
///////////////////////////////////////////////////////////////////////////////

#include <csignal>
#if defined(__WINDOWS__)
#include <crtdbg.h>
#endif

#include <yxs/util/XmlFile.h>
#include <yxs/net/SocketManager.h>

#include "Log.h"
#include "Database.h"
#include "RealmdSocketFactory.h"
#include "RealmList.h"

__MWOW_DB_ gLoginDB;
RealmList gRealmList;
static __YXS_SSM_ *_gssm_;

void __signal_handler(int signal)
{
    if (signal == SIGINT)
    {
        _gssm_->Close();
    }
}

::std::string FindConfigFile(int argc, char* argv[])
{
    if (argc >= 3)
    {
        if (strncmp(argv[1], "-f", 2) == 0)
        {
            return argv[2];
        }
    }

    return "./realmd.xml";
}

int main(int argc, char *argv[])
{
#if defined(__WINDOWS__)
    WSADATA wsa;
    WSAStartup(MAKEWORD(2,2), &wsa);
#endif
    
    {
        do 
        {
            Log::New();

            if (!__YXS_SQLDB_::CheckSanity())
            {
                MWOW_CRITICAL << "sanity check failed";
                break;
            }

            __YXS_XMLFILE_ cfg(FindConfigFile(argc, argv));
            ::std::string host = cfg.Get<::std::string>("realmd.host");
            short port = cfg.Get<short>("realmd.port");
            int backlog = cfg.Get<int>("realmd.backlog");
            int thread = cfg.Get<int>("realmd.thread");
            ::std::string db = cfg.Get<::std::string>("realmd.db");

            MWOW_INFO << "conf: " << host << "," << port << "," << backlog << "," << thread << "," << db;

            if (!gLoginDB.Initialize(db))
            {
                MWOW_CRITICAL << "login database initialize failed";
                break;
            }

            __YXS_SSM_ sockMgr(__YXS_SSF_PTR_(new RealmdSocketFactory()));
            if (sockMgr.Open(host, port, backlog, thread))
            {
                _gssm_ = &sockMgr;

                MWOW_INFO << "realmd startup";

                ::signal(SIGINT, __signal_handler);
                sockMgr.Join();
            }

            gRealmList.Clear();
            gLoginDB.Close();
        } while (false);

        Log::Free();
    }

#if defined(__WINDOWS__)
    WSACleanup();
    _CrtDumpMemoryLeaks();
#endif

    return 0;
}